//
//  MainAreaViewModel.m
//  GLGW_Shoping
//
//  Created by whx on 2018/12/20.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "MainAreaViewModel.h"
#import "NoDataFootTableViewHeaderFooterView.h"
#import "WithDrawlRecordDetailTableViewCell.h"
#import "MainTypesListHeaderView.h"
#import "MainAreaModel.h"
#import "MainArealCitysModel.h"
#import "MainAreaHeaderView.h"
#import "MainTypesListTopTableViewCell.h"
#import "UITableView+SCIndexView.h"
#import "SectionItem.h"

@interface MainAreaViewModel()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate, UITextFieldDelegate>
{
    UITableView *selfTableView;
}

@property (nonatomic, strong) MainAreaModel *model;
@property (nonatomic, strong) NSMutableArray *citysArr;                  // 排好序的城市列表
@property (nonatomic, strong) NSMutableArray *selectDataArr;             // 选中的cell在顶部显示数据
@property (nonatomic, copy) NSArray<NSString *> *tableViewDataSource;
@property (nonatomic, assign) BOOL translucent;

@end

@implementation MainAreaViewModel

- (instancetype)initWithViewToViewModel:(UITableView *)tableView theSuperView:(UIView *)superView
{
    if (self = [super initWithViewToViewModel:tableView theSuperView:superView]) {
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
        tableView.sectionFooterHeight = 0.0;
        tableView.sectionHeaderHeight = 10.0;
        tableView.mj_header.hidden = YES;
        tableView.mj_footer.hidden = YES;
        [tableView registerClass:[NoDataFootTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"NoDataFootTableViewHeaderFooterView"];
        [tableView registerClass:[MainTypesListHeaderView class] forHeaderFooterViewReuseIdentifier:@"MainTypesListHeaderView"];
        [tableView registerClass:[MainAreaHeaderView class] forHeaderFooterViewReuseIdentifier:@"MainAreaHeaderView"];
        selfTableView = tableView;
        [superView addSubview:tableView];
        
        self.translucent = YES;
        SCIndexViewConfiguration *configuration = [SCIndexViewConfiguration configurationWithIndexViewStyle:self.indexViewStyle];
        configuration.indexItemTextColor = kColor_Rule_Yellow;
        configuration.indexItemSelectedTextColor = kColor_Rule_Yellow;
        configuration.indexItemSelectedBackgroundColor = [UIColor clearColor];
        selfTableView.sc_indexViewConfiguration = configuration;
        selfTableView.sc_translucentForTableViewInNavigationBar = self.translucent;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Indexes" ofType:@"plist"];
            NSArray<SectionItem *> *tableViewDataSource = [NSArray yy_modelArrayWithClass:SectionItem.class json:[NSArray arrayWithContentsOfFile:plistPath]];
            
            NSMutableArray *indexViewDataSource = [NSMutableArray array];
            for (SectionItem *item in tableViewDataSource) {
                [indexViewDataSource addObject:item.title];
            }
            [indexViewDataSource insertObject:@" " atIndex:0];
            dispatch_sync(dispatch_get_main_queue(), ^{
                self.tableViewDataSource = indexViewDataSource.copy;
                [self->selfTableView reloadData];
                self->selfTableView.sc_indexViewDataSource = indexViewDataSource.copy;
            });
        });
        
        self.model = [MainAreaModel new];
        [self requestAddStoreInformation];
    }
    return self;
}

#pragma mark-tableViewDelegate And tableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return kHeightProportion_In_iPhoneTriploid(10);
    }
    return kHeightProportion_In_iPhoneTriploid(28);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    NoDataFootTableViewHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"NoDataFootTableViewHeaderFooterView"];
    return footer;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        MainTypesListHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MainTypesListHeaderView"];
        return view;
    }
    MainAreaHeaderView *headerV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MainAreaHeaderView"];
    headerV.leftStr = self.tableViewDataSource[section];
    return headerV;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.tableViewDataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return [self.citysArr[section - 1] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        MainTypesListTopTableViewCell *cell = [MainTypesListTopTableViewCell cellWithTableView:tableView];
        cell.arr = self.selectDataArr;
        return cell;
    }
    WithDrawlRecordDetailTableViewCell *detailCell = [WithDrawlRecordDetailTableViewCell cellWithTableView:tableView];
    detailCell.leftColorStr = @"#000000";
    detailCell.rightLab.hidden = YES;
    detailCell.showPush = NO;
    if ([self.citysArr[indexPath.section -1] count] > 0) {
        MainAreaListModel *deModel = self.citysArr[indexPath.section - 1][indexPath.row];
        detailCell.leftStr = deModel.provinceName;
    }
    return detailCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.citysArr[indexPath.section - 1] count] <= 0) return;
    [self makeData:indexPath];
    if (self.BlockSelecRow) {
        self.BlockSelecRow(self.dic);
    }
}

- (void)makeData:(NSIndexPath *)indexPath
{
    MainAreaListModel *deModel = self.citysArr[indexPath.section - 1][indexPath.row];
    NSDictionary *liD = @{
                          @"one" : indexPath,
                          @"two" : deModel
                          };
    NSMutableArray *arr = self.dic[@"arr"];
    BOOL isAdd = NO;
    if (arr.count <= 0) {
        [arr addObject:[liD mutableCopy]];
        self.dic[@"arr"] = arr;
        _dic[@"select"] = [NSString stringWithFormat:@"0"];
    } else {
        for (int i = 0; i < arr.count; i ++) {
            NSMutableDictionary *liDic = arr[i];
            NSIndexPath *seleIndex = liDic[@"one"];
            if (seleIndex == indexPath) {  // 没有选中的省城市的数据
                _dic[@"select"] = [NSString stringWithFormat:@"%d",i];
                isAdd = NO;
                break;
            } else {
                isAdd = YES;
            }
        }
        if (isAdd) {
            [arr addObject:[liD mutableCopy]];
            self.dic[@"arr"] = arr;
            _dic[@"select"] = [NSString stringWithFormat:@"%ld",arr.count -1];
        }
    }
}

// 从上个页面带过来的选中数据
- (void)makeLastPageSelectDic:(NSMutableDictionary *)dic
{
    self.dic = dic;
    // 刷新最上面显示的数据
    NSArray *liArr = dic[@"arr"];
    if (liArr.count <= 0) return;
    NSMutableArray *seleArr = [NSMutableArray array];
    for (int i = 0; i <  liArr.count; i ++) {
        NSDictionary *liDic = liArr[i];
        MainAreaListModel *arealListModel = liDic[@"two"];
        NSArray *citysArr = liDic[@"four"];
        if (citysArr.count > 0) {
            NSString *seleAppendStr;
            for (int i = 0; i < citysArr.count; i ++) {
                MainArealCitysListModel *citysListModel = citysArr[i];
                seleAppendStr = [NSString stringWithFormat:@"%@%@",arealListModel.provinceName,citysListModel.cityName];
                [seleArr addObject:seleAppendStr];
            }
        }
    }
    self.selectDataArr = seleArr;
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    [selfTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (NSMutableDictionary *)dic
{
    if (!_dic) {
        _dic = [NSMutableDictionary dictionary];
        _dic[@"select"] = @"-1";
        _dic[@"arr"] = [NSMutableArray array];
    }
    return _dic;
}

- (NSMutableArray *)selectDataArr
{
    if (!_selectDataArr) {
        _selectDataArr = [NSMutableArray array];
    }
    return _selectDataArr;
}

#pragma mark - 请求接口
// 获取省列表
- (void)requestAddStoreInformation
{
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kAreaProvince] lodingView:nil lodingTextString:@"" isLoding:YES parameters:@{} success:^(id  _Nullable response) {
        self.model = [MainAreaModel yy_modelWithJSON:response];
        if (self.model.code == 0) {
           self.citysArr = [NSMutableArray arrayWithArray:[self p_makeCityGroup:self.model.data]];
            [self->selfTableView reloadData];
        }
    } failure:^(NSError * _Nullable error) {
        DLog(@"====%@",error);
    }];
}

// 对城市按照首字母分组
- (NSArray *)p_makeCityGroup:(NSArray *)cityArray{
    NSMutableArray *letterDictArray = [NSMutableArray array];
    //创建26个数组用来存储
    for (int i = 0; i < 26; i ++) {
        NSMutableArray *letterCityArray = [NSMutableArray array];
        [letterDictArray addObject:letterCityArray];
    }
    for (MainAreaListModel *model in cityArray) {
        //将城市首字母转化为ASCII码
        int asciiCode = [model.pinyin characterAtIndex:0];
        int index = asciiCode - 65;
        [letterDictArray[index] addObject:model];
    }
    return [letterDictArray copy];
} 
@end
